//跟进计划列表
var $followPlanTable = $('#followPlanForm');

let companyNameStatic=''
//防止表头与表格不对齐
$(window).resize(function () {
    $followPlanTable.bootstrapTable('resetView');
});

$(function () {
    // 初始化日期选择控件
    $('#planDate').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    $('#startDate').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    $('#endDate').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });
    $('#planDate').datepicker({
        language: "zh-CN",
        autoclose: true,
        clearBtn: true,
        todayHighlight: true,
        format: "yyyy-mm-dd"
    });

    //初始化跟进计划列表
    followPlanFormList();

    ifSys();

    //公司列表
    loadAllCompanyList("companyName");

    $('#planStatus').selectpicker('refresh');
    getCustomerSelect('');
    $('#addFollowBtn').on('click', function () {
        $('#addInputMoney').modal('show');
        $('#addInputMoney .modal-header h4').html('新增跟进计划');
        $('#customerType').show(0);

        $("#cpFollowPlanIdHide").val('');
        $('#name').attr('disabled',false);
        $('#phone').attr('disabled',false);



    })

    $('#addInputMoney').on('hidden.bs.modal', function () {
        $(this).find('input').val('');
        $(this).find('select').val('').selectpicker('refresh');
    })

})

function followPlanFormList() {
//先销毁表格
    $followPlanTable.bootstrapTable('destroy');
    $followPlanTable.bootstrapTable({
        classes: 'table table-hover table-bordered',
        url: '/followPlan/followPlanList',//请求地址
        method: 'post',//请求方式
        contentType: "application/x-www-form-urlencoded",//请求内容类型
        dataType: "json",//数据类型
        striped: false,//是否显示行间隔色
        sortable: true,//是否启用排序
        sortOrder: "desc",//排序方式
        sortName: 'createTm',//排序字段
        cache: false,//是否使用缓存
        showColumns: false,//显示隐藏列
        showRefresh: false,//显示刷新按钮
        showToggle: false,//切换显示样式
        showFooter: false,//显示Table脚部
        pagination: true,//是否显示分页
        showPaginationSwitch: false,//是否显示分页按钮
        clickToSelect: false,//是否启用点击选中行
        singleSelect: false,
        minimumCountColumns: 2,//最少要显示的列数
        undefinedText: '-',//cell没有值时显示
        sidePagination: "server",//分页方式：client客户端分页，server服务端分页
        uniqueId: 'cpFollowPlanId',
        idField: 'cpFollowPlanId',
        pageSize: globalPageSize,//每页的记录行数
        pageNumber: 1,//初始化加载第1页，默认第1页
        pageList: globalPageList,//可供选择的每页的行数
        queryParams: queryParams,//查询参数
        columns: [
            {title: '主键', field: 'cpFollowPlanId', visible: false},
            {title: '序号', field: 'index', align: 'center', valign: 'left', width: '60', formatter: indexFormat},
            {title: '客户名称', field: 'customerName', align: 'left', valign: 'middle',formatter: customerNameFormat},
            // {title: '联系人', field: 'contactPerson', align: 'left', valign: 'middle',formatter :contactNameFormat},
            {title: '计划跟进时间', field: 'planDate', align: 'left', valign: 'middle', sortable: true},
            {title: '是否提醒', field: 'planStatus', align: 'left', valign: 'middle', formatter: planStatusToString},
            {title: '所有人', field: 'createPeopleName', align: 'left', valign: 'middle', visible: false},
            {title: '所属分公司', field: 'companyName', align: 'left', valign: 'middle', visible: false},
            {title: '操作', field: 'operate', align: 'right', events: editInfo, formatter: genderOpt}
        ],
        responseHandler: function (result) {
            if (result.code == "000000") {
                var obj = {
                    "rows": result.data,
                    "total": result.totalRecords//总条数
                };
            } else {
                var obj = {
                    "total": 0,
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function () {
            //加载成功时执行
            $("[data-toggle='tooltip']").tooltip();//加这个是为了让操作列的提示图标显示在上方

            // table列可拖动宽度
            $('.JCLRgrips').remove();
            $('#orderTableList').css({
                minWidth: $('#orderTableList').width()
            }).colResizable({
                resizeMode: 'overflow',
                liveDrag: true,
                gripInnerHtml: "<div class='grip'></div>",
                draggingClass: "dragging",
                disabledColumns: [0, 11,],      // 禁止拖动的列
                postbackSafe: true,                                         // 刷新后保持拖动的宽度
                partialRefresh: true,                                       // 刷新表格之后继续保持可拖动功能
                flush: true,
                minWidth: 80,
                /*onResize: function () {
                }*/
            });
        },
        onLoadError: function (status) {
            if (status == 403) {
                alert("权限不足！禁止访问！");
            } else {
                //加载失败时执行
                alert("加载失败！");
            }
        },
        formatLoadingMessage: function () {
            return "请稍等，加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
    });
}

/**
 * 点击客户姓名跳转客户详情页面
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function customerNameFormat(value, row, index) {
    if(value == null) {
        return '<span href="JavaScript:void(0);">-</span>';
    }else{
        return '<a href="JavaScript:void(0);" onclick=\'customerDetail(\"'+row.customerId+'")\'>'+value+'</a>';
    }

}

function  customerDetail(customerId) {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: '客户详情',
        url: "/front/user/customerManager/customerDetail?customerId=" + customerId
    },true);
}

/**
 * 点击联系人姓名跳转联系人详情页面
 * @param value
 * @param row
 * @param index
 * @returns {string}
 */
function contactNameFormat(value, row, index) {
    if(!value) {
        return '-';
    }
    return '<a href="JavaScript:void(0);"   onclick=\'contactDetail(\"'+row.contactPerson+'",\"'+row.contactPersonPhone+'",\"'+row.customerId+'")\'>'+value+'</a>';
}

function  contactDetail(contactName,contactInformation,customerId) {
    var contactId = "";

    //查询联系人id,进行跳转
    $.ajax({
        url: '/contact/getContactId',
        type: 'POST',
        dataType: "json",
        data: {
            customerId: customerId,
            contactInformation : contactInformation,
            contactName : contactName
        },
        success: (function (data) {
            if (data.code == "000000") {
                if (data.data.contactId != null) {
                    contactId = data.data.contactId;
                    parent.$(parent.document).data('multitabs').create({
                        iframe: true,
                        title: '联系人详情',
                        url: "/front/user/contactManager/contactDetail?contactId=" + contactId
                    },true);
                }
            } else {
                alert("操作失败");
            }
        }),
        error: (function () {
            alert("失败");
        })
    });

}

// 新增计划数据
function addFollowPlan() {
    var cpFollowPlanId = $("#cpFollowPlanIdHide").val();
    var contactPerson = $("#name").val();                   // 联系人姓名
    var contactPersonPhone = $("#phone").val();             // 联系人电话
    var planDate = $.trim($('#planDate').val());            // 计划跟进时间
    var planStatus = $.trim($('#planStatus').val());        // 是否提醒

    if (!contactPerson) {
        $.alert('联系人姓名不能为空');
        return;
    }
    if (!contactPersonPhone) {
        $.alert('联系人电话不能为空');
        return;
    }
    if (!planDate) {
        $.alert('计划跟进时间不能为空');
        return;
    }
    if (!planStatus) {
        $.alert('是否提醒不能为空');
        return;
    }

    if (cpFollowPlanId) {
        var customerId = $('#customerId').val(); //客户id
        var jsonData = {
            "customerId": customerId,
            "planDate": planDate,
            "planStatus": planStatus,
            "contactPerson": contactPerson,
            "contactPersonPhone": contactPersonPhone,
            "cpFollowPlanId": cpFollowPlanId
        }
        $.ajax({
            url: '/followPlan/updateFollowPlan',
            type: 'POST',
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(jsonData),
            success: (function (data) {
                if (data.code == '000000') {
                    $('#addInputMoney').modal('hide');
                    $('#followPlanForm').bootstrapTable('refresh');
                } else {
                    $.alert(data.message);
                }
            }),
            error: (function (res) {
                $.alert("保存失败");
            })
        })
    } else {
        var customerId = $.trim($('#customerInput').val()); //客户id
        if (!customerId) {
            $.alert('客户名称不能为空');
            return;
        }
        var jsonData = {
            "customerId": customerId,
            "planDate": planDate,
            "contactPerson": contactPerson,
            "contactPersonPhone": contactPersonPhone,
            "planStatus": planStatus
        }
        $.ajax({
            url: '/followPlan/addFollowPlan',
            type: 'POST',
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(jsonData),
            success: (function (data) {
                if (data.code == '000000') {
                    $('#addInputMoney').modal('hide');
                    $('#followPlanForm').bootstrapTable('refresh');
                    /*$.alert({
                        title: '提示',
                        content: '保存成功！',
                        buttons: {
                            confirm: {
                                text: '确认',
                                btnClass: 'btn-primary',
                                action: function () {
                                    //页面跳转赋值
                                    var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                                    var navTab = parent.$multitabs._getNavTab($thisTabs);
                                    window.location.reload();
                                }
                            }
                        }
                    });*/
                } else {
                    $.alert(data.message);
                }
            }),
            error: (function (res) {
                $.alert("保存失败");
            })
        })
    }
}

function searchOrderList(type) {
    $('.all').addClass('active-second');
    $('.today').removeClass('active-second');
    $('.week').removeClass('active-second');
    $('.month').removeClass('active-second');
    $('.year').removeClass('active-second');
    $("#dateType").val("all");
    if (type === 1) {//普通条件查询
        $followPlanTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams2});
        // 点击搜索重置表单并收起高级搜索 需传入高级搜索id #filterContent
        $('#filterContent').collapse('hide').on('hidden.bs.collapse', function () {
            resetOrderQueryParams('#filterContent');
        });
    } else if (type == 2) {//高级搜索条件查询
        $('#orderNumberMin').val('');
        $followPlanTable.bootstrapTable('refreshOptions', {pageNumber: 1, queryParams: queryParams});
    }
}

function queryParams(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.isAdmin = $.trim($('#qx').val());//权限
    //搜索条件
    params.customerName = $.trim($('#customerName2').val());//客户名称
    params.contactPerson = $.trim($('#contactPerson').val());//联系人
    params.startDate = $.trim($('#startDate').val());//开始计划日期
    params.endDate = $.trim($('#endDate').val());//截止计划日期
    params.companyId = $.trim($('#companyName').val());//公司
    params.createPeopleName = $.trim($('#createPeopleName').val());//所属人
    params.dateType = $('#dateType').val();
    params.followType = $('#followType').val();
    return params;
}

function queryParams2(params) {
    params.pageSize = params.limit;
    params.pageIndex = (params.offset / params.limit) + 1;
    params.sortName = params.sort; //排序列名
    params.sortOrder = params.order;//排序方式
    params.isAdmin = $.trim($('#qx').val());//权限
    //搜索条件
    params.customerName = $.trim($('#customerName').val());//客户名称
    params.dateType = $('#dateType').val();
    params.followType = $('#followType').val();
    return params;
}

//重置高级查询
function clearAllData() {
    $('#customerName2').val('');
    $('#contactPerson').val('');
    $('#startDate').val('');
    $('#endDate').val('');
    $('#createPeopleName').val('');
    // window.location.reload();
}

/**
 * 自定义操作列内容
 */
function genderOpt(value, row, index) {
    let html = '';
    html += '<button type="button" class="btn btn-default" onclick="followUpPlan(\'' +row.customerId + '\',\'' +row.planDate + '\')">详情</button>';
    html += '<button type="button" class="btn btn-default" id="editInfo">修改</button>';

    let today = new Date().Format('yyyy-MM-dd')
    var v=$.trim($('#isAdmin').val());
    if (v == "" && $("#qx").val() == 2){//只限制用户
        if(row.planDate == today){//判断是否是当天的计划
            html += '<button type="button" class="btn btn-default" onclick="delFollowPlan(\'' + row.cpFollowPlanId + '\',1)">取消</button>';
        }
    }else{
        html += '<button type="button" class="btn btn-default" onclick="delFollowPlan(\'' + row.cpFollowPlanId + '\',2)">取消</button>';
    }
    html += '</ul></div>'
    return html;
}

var editInfo = {
    'click #editInfo': function(e, value, row, index) {
        // 修改标题

        // console.log(row,'row==',row.customerName)
        $('#addInputMoney .modal-header h4').html('修改跟进计划');
        // 隐藏客户名称字段
        $('#customerType').hide(0);

        $("#cpFollowPlanIdHide").val(row.cpFollowPlanId);
        $('#customerId').val(row.customerId);

        $('#name').val(row.contactPerson);
        $('#phone').val(row.contactPersonPhone);
        $('#planDate').val(row.planDate);
        $('#planStatus').val(row.planStatus).selectpicker('refresh');



        $('#addInputMoney').modal('show');
        $('#name').attr('disabled',true);
        $('#phone').attr('disabled',true);
        if(companyNameStatic){
            let companyData = '';
            $.each(companyNameStatic, function (n, value) {
                // console.log(name,'name==',name==value.customerName)
                if(row.customerName==value.customerName){
                    companyData += '<option value="' + value.customerId + '" selected>' + value.customerName + '</option>';
                }else{
                    companyData += '<option value="' + value.customerId + '">' + value.customerName + '</option>';
                }

            });
            // $('#customerInput').html(html).attr('disabled', false).selectpicker('refresh');
            $("#customerInput").val(row.customerName)
            $('#customerInput').html(companyData).selectpicker('refresh');
        }
        else{
            getCustomerSelect(row.customerName)
        }

    }
}

//跟进计划详情页面
function followUpPlan(id,time) {
    parent.$(parent.document).data('multitabs').create({
        iframe: true,
        title: "跟进计划详情",
        url: "/front/followPlanManager/followPlanInfo?customerId="+id+"&planDate="+time
    }, true);
}

//修改回显
// var customerIdexistence;

function updateFollowPlan(cpFollowPlanId, customerId, planStatus, planDate) {
    // 修改标题
    $('#addInputMoney .modal-header h4').html('修改跟进计划');
    // 隐藏客户名称字段
    $('#customerType').hide(0);


    $("#cpFollowPlanIdHide").val(cpFollowPlanId);
    // customerIdexistence = customerId
    // $("#customerInput").val(customerId);

    $("#planStatus").val(planStatus);
    $("#planDate").val(planDate);


}

function indexFormat(value, row, index) {
    return index + 1;
}

function selectPlan(type) {

    if (type == 'followAll') {//全部跟进
        $("#followType").val("followAll");
        $(".followAll").addClass("active-second")
        $(".followAll").siblings().removeClass("active-second")
    }
    if (type == 'plan') {//计划跟进
        $("#followType").val("plan");
        $(".plan").addClass("active-second")
        $(".plan").siblings().removeClass("active-second")
    }
    $followPlanTable.bootstrapTable('refreshOptions', {pageNumber: 1});
}

/**
 * 全部/周/月/年切换
 * @param time
 */
function selectTime(time) {
    if (time == 'all') {//全部
        $('.all').addClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("all");
    }
    if (time == 'year') {//本年
        $('.year').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisYear");
    }
    if (time == 'month') {//本月
        $('.month').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.week').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisMonth");
    }
    if (time == 'week') {//本周
        $('.week').addClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $('.today').removeClass('active-second');
        $("#dateType").val("thisWeek");
    }
    if (time == 'today') {//今天
        $('.today').addClass('active-second');
        $('.week').removeClass('active-second');
        $('.all').removeClass('active-second');
        $('.year').removeClass('active-second');
        $('.month').removeClass('active-second');
        $("#dateType").val("thisToday");
    }
    $followPlanTable.bootstrapTable('refreshOptions', {pageNumber: 1});
}

/**
 * 获得客户名称下拉
 */
function getCustomerSelect(name) {
    var qx = $("#qx").val();
    var url = '/customerController/getCustomerListByComp'
    if (qx == 2){
        url = '/customerController/getCustomerList'
    }
    $.ajax({
        type: 'POST',
        dataType: "json",
        url: url,
        // cache: false,
        // data: {},
        async: true,
        success: (function (data) {
            if (data.code == "000000") {
                companyNameStatic=data.data
                var html = '';
                $.each(data.data, function (n, value) {
                    // console.log(name,'name==',name==value.customerName)
                    if(name==value.customerName){
                        html += '<option value="' + value.customerId + '" selected>' + value.customerName + '</option>';
                    }else{
                        html += '<option value="' + value.customerId + '">' + value.customerName + '</option>';
                    }

                });
                // $('#customerInput').html(html).attr('disabled', false).selectpicker('refresh');
                $("#customerInput").val(name)
                $('#customerInput').html(html).selectpicker('refresh');

            } else {
                alert("请求失败");
            }
        }),
        error: (function (res) {
            alert("请求失败");
        }),
        beforeSend:function () {
            $('#customerInput').selectpicker('destroy').html('<option value="加载中...">加载中...</option>')

        }
    });
}

//删除计划
//type用于判断是否是普通用户，只限制普通用户
function delFollowPlan(cpFollowPlanId,type) {
    $.ajax({
        type: 'POST',
        dataType: "json",
        url: '/followPlan/deleteFollowPlan',
        cache: false,
        data: {
            "cpFollowPlanId": cpFollowPlanId,
            "type":type
        },
        async: false,
        success: (function (data) {
            if (data.code == "000000") {
                $.alert({
                    title: '提示',
                    content: '取消成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                $followPlanTable.bootstrapTable('refresh');
                            }
                        }
                    }
                });
            } else if (data.code == '800000'){
                alert("已完成计划不允许被取消");
            } else {
                alert("请求失败");
            }
        }),
        error: (function (res) {
            alert("请求失败");
        })
    });
}

// 获取联系人
function changeName(_this) {
    var $this = _this;
    //联系人姓名
    var name = $.trim($("#name").val());
    //从哪跳转到跟进页面（0：线索；1：客户）
    var source = 1;
    //线索/客户id
    var id = $("#customerInput").val();
    var status;
    if (!name) {
        status = '0';
    } else {
        status = '1';
    }
    $.ajax({
        url: '/clueContact/clueContact/echo',
        data: {
            name: name,
            status: status,
            id: id,
            source: source
        },
        type: "POST",
        contentType: "application/x-www-form-urlencoded",
        success: function (data) {
            if (data.code == '000000') {
                $("#nameBox").css("display", 'block');
                $("#nameBox").html('');
                if (data.data.length <= 0) {//把页面上之前赋值的联系人id置空
                } else {
                    let str = '';
                    for (let i = 0; i < data.data.length; i++) {
                        str += '<li><a href="javascript:void(0);" class="name-item" onclick="getTel(\'' + data.data[i].contactName + '\',\'' + data.data[i].contactInformation + '\')">' + data.data[i].contactName + '</a></li>'
                    }
                    $("#nameBox").html(str);
                }
            }
        }
    });

    // 点击输入框和下拉菜单以外范围，关闭提示下拉菜单
    $(document).click(function (e) {
        var con = $($this).parents('.form-content');
        if (!con.is(e.target) && con.has(e.target).length === 0) {
            $("#nameBox").slideUp(160);
        }
    })
}

function getTel(name, phone) {
    $("#name").val(name);
    $("#phone").val(phone);
    $("#nameBox").css("display", 'none');
}

function planStatusToString(value, row, index) {
    if (row.planStatus== 0){
        return "<span><img src='../../../images/no-icon.png' alt='' style='margin-right: 10px;width: 15px;height: 15px'>否</span>";
    }else if (row.planStatus== 1){
        return "<span><img src='../../../images/yes-icon.png' alt='' style='margin-right: 10px;width: 15px;height: 15px'>是</span>";
    }else {
        return "";
    }
}

function ifSys() {
    var v=$.trim($('#isAdmin').val());
    if (v == "false"){
        if ( $("#qx").val() == 1){
            $('#companyNameDiv').css('display', 'none');
            $followPlanTable.bootstrapTable('showColumn', "createPeopleName");
        }
    }else if (v){
        $followPlanTable.bootstrapTable('showColumn', "createPeopleName");
        $followPlanTable.bootstrapTable('showColumn', "companyName");
    }
}

/**
 * 加载全部公司信息并且赋值到select框
 */
function loadAllCompanyList(name) {
    $.getJSON("/company/getCompanyList", function (data) {
        if (data.code == '000000') {
            var companyOptionHtml = '<option value="">请选择</option>';
            data.data.map(function (item) {
                companyOptionHtml += '<option value="' + item.companyId + '">' + item.companyName + '</option>';
            });
            $('#' + name).html("");
            $('#' + name).append(companyOptionHtml);
            $('#' + name).selectpicker('refresh');
        }
    });
}

